<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Models\Children;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class UsersController extends Controller
{
    public function index(Request $request){
        $data = '';
        if ($request->isMethod('post')){
            $data = $request->table_search;
        }
        $users = User::where('name', 'like', '%'.$data.'%')
                ->orwhere('mobile', 'like', '%'.$data.'%')
                ->paginate(config('constants.page_num'));
        return view('admin.users.index', compact('users'));
    }

    public function create(){
        return view('admin.users.create');
    }

    public function store(Requests\UsersRequest $request){
        $data = $request->all();
        $data['t_id'] = Auth::guard('admin')->user()->id;
        $result = User::create($data);
        if ($result){
            exit(json_encode(array('code'=>1, 'url'=>'/admin/users')));
        }else{
            exit(json_encode(array('code'=>0, 'msg'=>$result)));
        }
    }

    public function show($id){
        $user = User::findOrFail($id);
        $children = Children::where('p_id', '=', $id)->get();
        return view('admin.users.show', compact('user', 'children'));
    }

    public function edit($id){
        $user = User::findOrFail($id);
        return view('admin.users.edit', compact('user'));
    }

    public function update(Requests\UsersRequest $request, $id){
        $user = User::findOrFail($id);
        $result = $user->update($request->all());
        if ($result){
            exit(json_encode(array('code'=>1, 'url'=>'/admin/users/'.$id)));
        }else{
            exit(json_encode(array('code'=>0, 'msg'=>$result)));
        }
    }

    public function destroy($id){
        $user = User::findOrFail($id);
        $user->status = $user->status ? 0 : 1;
        if ($user->save()){
            exit(json_encode(array('code'=>1)));
        } else {
            exit(json_encode(array('code'=>0)));
        }
    }
}
